<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>场景移动</title>
    <style>
        body {
            background-color: black;
        }
        
        #canvas {
            border: 2px solid white;
            position: absolute;
            width: 1000px;
            height: 700px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>

<body>
    <canvas id="canvas"></canvas>
    <script>
        const canvas = document.querySelector("#canvas")
        const ctx = canvas.getContext('2d')
        const CANVAS_WIDTH = canvas.width = 1000
        const CANVAS_HEIGHT = canvas.height = 700

        const bgLayer1 = new Image()
        bgLayer1.src = 'imgs/layer-1.png'

        const bgLayer2 = new Image()
        bgLayer2.src = 'imgs/layer-2.png'

        const bgLayer3 = new Image()
        bgLayer3.src = 'imgs/layer-3.png'

        const bgLayer4 = new Image()
        bgLayer4.src = 'imgs/layer-4.png'

        const bgLayer5 = new Image()
        bgLayer5.src = 'imgs/layer-5.png'


        let gameSpeed = 10

        class Layer {
            constructor(image, speedModifier) {
                this.x = 0
                this.y = 0

                this.width = 2400
                this.height = 700
                this.x2 = this.width
                this.image = image
                this.speedModifier = speedModifier
                this.speed = gameSpeed * this.speedModifier
            }

            draw() {
                ctx.drawImage(this.image, this.x, this.y, this.width, this.height)
                ctx.drawImage(this.image, this.x2, this.y, this.width, this.height)
            }

            update() {
                this.speed = gameSpeed * this.speedModifier
                if (this.x <= -this.width) {
                    this.x = this.width + this.x2 - this.speed
                }
                if (this.x2 <= -this.width) {
                    this.x2 = this.width + this.x - this.speed
                }

                this.x = Math.floor(this.x - this.speed)
                this.x2 = Math.floor(this.x2 - this.speed)
            }
        }

        const Layers = [new Layer(bgLayer1, 0.2), new Layer(bgLayer2, 0.4),
            new Layer(bgLayer3, 0.6), new Layer(bgLayer4, 0.8), new Layer(bgLayer5, 1)
        ]

        function animate() {
            ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT)

            Layers.forEach(Layer => {
                layer.update()
                layer.draw()
            })
        }

        window.requestAnimationFrame(animate)
    </script>
</body>

</html>